<template>
  <div ref="chartRef" :style="{ height }" />
</template>

<script>
import {
  defineComponent,
  getCurrentInstance,
  onMounted,
  onBeforeMount,
  onBeforeUnmount,
  nextTick,
  watchEffect,
} from 'vue';
//引入echarts
import * as echarts from 'echarts';
import china from './mapData/map.json';
const chartsArr = [];
export default defineComponent({
  name: 'Echarts',
  props: {
    height: {
      type: String,
      default: '100%',
    },
    options: {
      type: Object,
      default: () => ({}),
    },
  },
  setup(props) {
    //setup执行时组件对象还没有创建，我们可以通过 getCurrentInstance这个函数来返回当前组件的实例对象
    const { proxy } = getCurrentInstance();
    const initCharts = () => {
      //通过Promise异步操作,避免报错Initialize failed: invalid dom
      //1:新建一个promise对象
      const newPromise = new Promise((resolve) => {
        resolve();
      });
      // 2:然后异步执行echarts的初始化函数
      newPromise.then(() => {
        const myChart = echarts.init(proxy.$refs.chartRef);
        echarts.registerMap('china', china);
        watchEffect(() => {
          myChart.setOption(props.options);
        });
        chartsArr.push(myChart);
      });
    };
    //窗口resize事件
    const handleChartResize = () => {
      for (let i = 0; i < chartsArr.length; i++) {
        chartsArr[i] && chartsArr[i].resize();
      }
    };
    onBeforeMount(() => {
      nextTick(() => {
        initCharts();
      });
    });
    onMounted(() => {
      window.addEventListener('resize', handleChartResize);
    });
    onBeforeUnmount(() => {
      window.removeEventListener('resize', handleChartResize);
    });
    return {};
  },
});
</script>

<style lang="scss" scoped></style>
